package com.zzyl.intercept;

import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.constant.SuperConstant;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.utils.UserThreadLocal;
import com.zzyl.vo.UserVo;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 拦截所有的后端请求
 */
@Component
public class UserTokenInterceptor implements HandlerInterceptor {

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    /**
     * 执行目标方法之前执行 (controller方法)
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1. 判断当前的请求是否是请求后端的controller 如果不是则直接放行(html css png等静态资源)
        if(!(handler instanceof HandlerMethod)){
            return true;
        }

        //2. 从请求中获取token
        String token = request.getHeader(Constants.USER_TOKEN);

        //3. 判断token是否为空 为空返回401
        if(ObjectUtil.isEmpty(token)){
            //response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED_DISABLE);
        }

        //4. 解析并校验token
        Claims claims = JwtUtil.parseJWT(secretKey, token);

        //5. 判断解析的数据是否为空 如果为空则返回401
        if(ObjectUtil.isEmpty(claims)){
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED_DISABLE);
        }

        //6. 从token中获取登录的用户数据
        Object obj = claims.get("currentUser");
        if(ObjectUtil.isEmpty(obj)){
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED_DISABLE);
        }
        String userJson = JSONUtil.toJsonStr(obj);
        UserVo vo = JSONUtil.toBean(userJson, UserVo.class);

        //7. 构建redis的key 然后获取当前用户缓存在redis中的资源列表
        String json = redisTemplate.opsForValue().get(SuperConstant.USER_RESOURCE_ + vo.getId());
        if(ObjectUtil.isEmpty(json)){
            throw new BaseException(BasicEnum.ROLE_DISTRIBUTED_DISABLE);
        }
        List<String> pathUrls = JSONUtil.toList(json, String.class);

        //8. 获取当前请求的方式和路径
        String url = request.getMethod() + request.getRequestURI();

        //9. 判断当前请求的方式和路径是否在权限范围内如果在则返回true放行 如果不再则返回403
        for(int i=0; i<pathUrls.size(); i++){
            if(antPathMatcher.match(pathUrls.get(i),url)){
                //10. 向TheradLocal中存储当前登录的用户数据
                UserThreadLocal.setSubject(userJson);
                return  true;
            }
        }
        /*response.setStatus(HttpServletResponse.SC_FORBIDDEN);
        return false;*/
        throw new BaseException(BasicEnum.LOGIN_FAIL);
    }

    /**
     * 执行目标方法之后执行-清除threadlocal中的数据避免内存泄露
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        UserThreadLocal.remove();
    }
}
